package luj.tool.jnproxyan.proxy.network.socks.actor.root.message.admin.connect.rule;

import com.google.common.collect.ImmutableMap;
import luj.data.api.DataContext;
import luj.data.api.use.UseGroup;
import luj.tool.jnproxyan.proxy.database.DatabaseState;
import luj.tool.jnproxyan.proxy.rule.ConnectRules;
import luj.tool.jnproxyan.proxy.rule.RuleItem;
import luj.tool.jnproxyan.proxy.network.socks.actor.root.Socks5Actor;
import luj.tool.jnproxyan.proxy.network.socks.request.SocksRequest;
import luj.tool.jnproxyan.proxy.util.data.DataBeanCreator;
import luj.tool.jnproxyan.proxy.util.data.DataDirtySaver;
import luj.tool.jnproxyan.proxy.util.data.wrap.ResultGlobalLWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.Instant;

import static com.google.common.base.Preconditions.checkNotNull;

@Component
final class OnAddRule implements Socks5Actor.Handler<AddRuleMsg> {

  @Override
  public void onHandle(Context ctx) throws Exception {
    Socks5Actor self = ctx.getActorState(this);
    AddRuleMsg msg = ctx.getMessage(this);

    Long reqId = msg.requestId();
    SocksRequest req = self.getRequestMap().get(reqId);
    checkNotNull(req, reqId);

    DatabaseState dbState = self.getDatabaseState();
    UseGroup using = _lujdata.createUseGroup();
    RuleItem item = _dataMaker.createV2(RuleItem.class, using, dbState);
    item.createTime().set(Instant.now().toEpochMilli());

    String pattern = req.getBody().getTargetHost();
    item.targetHost().set(pattern);

    ConnectRules rule = _dataLoader.load(dbState, using).andWrap(ConnectRules.class);
    rule.itemMap().put(pattern, item);
    _dirtySaver.inject(dbState, using).save();

    msg.http().responsePage(ImmutableMap.of());
  }

  @Autowired
  DataContext _lujdata;

  @Autowired
  DataBeanCreator _dataMaker;

  @Autowired
  ResultGlobalLWrapper _dataLoader;

  @Autowired
  DataDirtySaver _dirtySaver;
}
